<?php
if (realpath(__FILE__) == realpath($_SERVER['SCRIPT_FILENAME'])) {exit('No Direct Access!');} 

/*
 +-----------------------------------------------------------------------+
 | Copyright (c) 2009 , Ersin Güvenç                                     |
 | All rights reserved.                                                  |
 |                                                                       |
 | EasyRest XML Library v 1.0                                            |
 | PHP VERSION 5                                                         |
 | LICENSE: GPL                                                          |
 |                                                                       |
 | Redistribution and use in source and binary forms, with or without    |
 | modification, are permitted provided that the following conditions    |
 | are met:                                                              |
 |                                                                       |
 | o Redistributions of source code must retain the above copyright      |
 |   notice, this list of conditions and the following disclaimer.       |
 | o Redistributions in binary form must reproduce the above copyright   |
 |   notice, this list of conditions and the following disclaimer in the |
 |   documentation and/or other materials provided with the distribution.|
 | o The names of the authors may not be used to endorse or promote      |
 |   products derived from this software without specific prior written  |
 |   permission.                                                         |
 |                                                                       |
 |  This program is free software: you can redistribute it and/or modify |
 |  it under the terms of the GNU General Public License as published by |
 |  the Free Software Foundation, either version 3 of the License, or    |
 |  (at your option) any later version.                                  |
 |                                                                       |
 |  This program is distributed in the hope that it will be useful,      |
 |  but WITHOUT ANY WARRANTY; without even the implied warranty of       |
 |  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        |
 |  GNU General Public License for more details.                         |
 |                                                                       |
 |  You should have received a copy of the GNU General Public License    |
 |  along with this program. If not, see <http://www.gnu.org/licenses/>  |
 |                                                                       |
 +-----------------------------------------------------------------------+
 | Author: Ersin Güvenç <eguvenc at gmail.com>                           |
 +-----------------------------------------------------------------------+
*/

/**
 * @category  WebServices
 * @package   EasyRest
 * @author    Ersin Güvenç <eguvenc@gmail.com>
 * @copyright 2009 Ersin Güvenç
 * @license   http://www.opensource.org/licenses/gpl-3.0.html GPL
 * @version   1.0
 * @filesource
 * @link      http://www.develturk.com
 * @see       
 * @since     1.0
 * 
 */
 
// EasyRest XML Class
// Serialize (write xml content) xml and Unserialize (convert xml content to array) functions.

 /**
* XML_Exception class
* @version 1.0
*/  
Class XML_Exception extends Easyrest_Exception{}

/**
* Rest_Serializer abstract class
* @version 1.0
*/
abstract class Rest_serializer
{
    // Simply serialize array to xml.
    public function serialize($data){}
    
    // Simply serialize xml to array.
    public function unserialize($data){}
}
         
                                                                 
Class Rest_xml extends Rest_serializer 
{
    /**
    * static object instance
    * @var object 
    */    
    private static $instance;
    
    /**
    * called secure function name
    * @var string 
    */  
    public $commandName = NULL;
    
    function __construct(){} //disable construct.
    
    private function __clone(){} //disabel clone.

    /**
    * Get the instantiated static object
    * @version 1.0
    * @return object instance
    */
    public static function getInstance()
    {
       if(! (self::$instance instanceof self))
       {
            self::$instance = new self();
       } 
       return self::$instance;
    }
    
    /**
    * Set current function name instead of static 
    * xml root tag 
    *
    * @version 1.0
    * @param string $commandName current func name.
    */
    public function _setCommand($commandName)
    {
        $this->commandName = $commandName;   
    }

    /**
    * Set serialize options
    * @version 1.0
    * @return array $options
    */
    private function set_serialize_options()
    {                                                                                        
        require_once (PEAR_LIB.'XML/Serializer.php');
                                  
        global $config;
        
        $options = array(
                    XML_SERIALIZER_OPTION_INDENT              => '    ',
                    XML_SERIALIZER_OPTION_LINEBREAKS          => $config['xml_serializer']['linebreaks'],
                    XML_SERIALIZER_OPTION_ROOT_NAME           => $this->commandName, //$config['xml_serializer']['default_tag']
                    XML_SERIALIZER_OPTION_XML_DECL_ENABLED    => FALSE,  //this is static, do not change it.
                    //add < xml version 1 head >
                    XML_SERIALIZER_OPTION_XML_ENCODING        => $config['xml_serializer']['xml_encoding'],
                    XML_SERIALIZER_OPTION_CDATA_SECTIONS      => $config['xml_serializer']['cdata'],
                    XML_SERIALIZER_OPTION_TYPEHINTS           => $config['xml_serializer']['type_hints'],
                    //XML_SERIALIZER_OPTION_ROOT_ATTRIBS => array('version' => '0.91'),
                    XML_SERIALIZER_OPTION_DEFAULT_TAG         => $config['xml_serializer']['default_tag'],
                    XML_SERIALIZER_OPTION_MODE                => XML_SERIALIZER_MODE_SIMPLEXML
                );
        
        return $options; 
    }
    

    /**
    * Serialize.
    * Write xml content (array to xml)
    * 
    * @version 1.0
    * @param array content
    * @return mixed $xml
    */
    function serialize($array)
    {
        global $config;
        
        if(!is_array($array))
        throw new XML_Exception('Serialize data must be an array!');
        
        $options = $this->set_serialize_options();
        
        /* we call xml serialize class with our options we had before */
        $serializer = new XML_Serializer($options);
        
        $result = $serializer->serialize($array);

        if ($result === TRUE)
        {                                           
            $xml = $serializer->getSerializedData();
            
        } else {
            
             if (PEAR::isError($result))
             {
                $xml = "<?xml version=\"1.0\" encoding=\"";
                $xml.= $config['xml_serializer']['xml_encoding'];
                $xml.= "\"?>";                                   
                $xml.= "<fault>";
                $xml.= "<string>".$result->getMessage()."</string>";
                $xml.= "<line>".__LINE__."</line>";
                $xml.= "</fault>";
            
             } 
            
        }
        
        return $xml;
    }
    
    /**
    * Set serialize options
    * 
    * @access private static
    * @version 1.0
    * @return array $options
    */
    private function set_unserialize_options()
    {
        require_once (PEAR_LIB.'XML/Unserializer.php');

        // complex structures are arrays, the key is the attribute 'handle' or 'name', if handle is not present
        $options = array(
                         XML_UNSERIALIZER_OPTION_COMPLEXTYPE => 'array',
                         XML_UNSERIALIZER_OPTION_ATTRIBUTES_PARSE => TRUE 
                         /*
                         XML_UNSERIALIZER_OPTION_ATTRIBUTE_KEY => array(
                                                                          'user'     => 'handle',
                                                                          'group'    => 'name',
                                                                          '#default' => 'id'
                                                                        ) 
                         */
                        );
        
        return $options;
    }
    
     /**
    * Unserialize
    * Convert xml content to array (xml to array)
    * 
    * @param mixed xml
    * @version 1.0
    * @return array $array result
    */
    function unserialize($xml)
    {
        $options = $this->set_unserialize_options();
        
        //  be careful to always use the ampersand in front of the new operator 
        $unserializer = new XML_Unserializer($options);

        // userialize the document
        $status = $unserializer->unserialize($xml, false);    

        if (PEAR::isError($status))
        {
            //echo 'Error: ' . $status->getMessage();
            //throw new XML_Exception($status->getMessage());
            $array = array('fault' => 
                          array(
                                'string' => $status->getMessage(),
                                'line'   => __LINE__)
                                );
            
        } else {
            $array = $unserializer->getUnserializedData();
            //echo '<pre>';
            //print_r($data);
            //echo '</pre>';
        }
        
        return $array;
    }


} //end of the class.


?>
